package cn.jellybmedia.org.service.impl;

import cn.jellybmedia.basic.service.impl.BaseServiceImpl;
import cn.jellybmedia.org.domain.Department;
import cn.jellybmedia.org.domain.Employee;
import cn.jellybmedia.org.mapper.DepartmentMapper;
import cn.jellybmedia.org.mapper.EmployeeMapper;
import cn.jellybmedia.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
* @Description: service层实现类
* @Author: Mr.She
* @Version: 1.0
* @Date:  2022/6/21 18:10  
*/

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;

    @Autowired
    private DepartmentMapper departmentMapper;





    @Override
    public List<Department> getTree() {
        // 获取全部的部门数据
        List<Department> departments = departmentMapper.loadAll();
        // 创建一个部门集合,用于存放新的部门树数据
        ArrayList<Department> departmentTree = new ArrayList<>();
        // 将获取到的全部部门数据转换成map集合
        HashMap<Long, Department> departmentMap = new HashMap<>();
        for (Department department : departments) {
            departmentMap.put(department.getId(), department);
        }


        // 进入for循环,循环得到的全部部门数据
        for (Department deptTmp : departments) {
            // 判断数据是否有父级id,如果没有,就是是第一级,
            if (deptTmp.getParentId() == null) {
                departmentTree.add(deptTmp);
            } else {
                // 如果有,就不是第一季,就通过自己id去找父亲的子级id
                Department department = departmentMap.get(deptTmp.getParentId());
                if (department != null) {
                    department.getChildren().add(deptTmp);
                }

            }
        }
        System.out.println("后端返回"+departmentTree);
        return departmentTree;

    }
}
